const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()

const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const koaBody = require('koa-body')
const logger = require('koa-logger')
const mongoose = require('mongoose')

const config = require('./config')

//router
const write = require('./routes/write')
const upload = require('./routes/upload')

//connect mongodb
mongoose.connect('mongodb://127.0.0.1:27017/myblog', {
  useNewUrlParser: true,
  useUnifiedTopology: true
})

// error handler
onerror(app)

// middlewares
app
  .use(
    koaBody({
      multipart: true
    })
  )
  .use(json())
  .use(router.routes())
  .use(router.allowedMethods())
  .use(logger())

app.use(write.routes()).use(write.allowedMethods())
app.use(upload.routes()).use(write.allowedMethods())

router.get('/', async ctx => {
  ctx.state = {
    title: 'Koa2'
  }
  await ctx.render('index', ctx.state)
})

app.on('error', function(err, ctx) {})

module.exports = app.listen(config.port, () => {
  console.log(`Listening on http://localhost:${config.port}`)
})
